<template>
  <div class="main">
    <a-form id="formLogin" class="user-layout-login" ref="formLogin" :form="form" @submit="handleSubmit">
      <div class="sjh">
        <h3>手机号登录注册</h3>
      </div>
      <a-form-item>
        <a-input
          size="large"
          type="text"
          autocomplete="off"
          placeholder="请输入手机号"
          v-decorator="[
            'user_name',
            {
              initialValue: '',
              rules: [{ validator: validFunction }],
              validateTrigger: 'blur',
            },
          ]"
          :maxLength="11"
        >
          <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
        </a-input>
      </a-form-item>

      <a-form-item class="yzm">
        <a-row>
          <a-col :span="16">
            <a-input
              size="large"
              autocomplete="off"
              placeholder="请输入验证码"
              v-decorator="[
                'code',
                { initialValue: '', rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur' },
              ]"
              :maxLength="6"
            >
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-col>
          <a-col :span="8" class="link">
            <a-spin :spinning="spinning"><a-button type="link" @click="getSms" v-show="smsShow"> 获取验证码 </a-button></a-spin>
            <a-button type="link" v-show="!smsShow"> {{ countText }} </a-button>
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item style="margin-top: 24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="state.loginBtn"
          :disabled="!checked"
          >登录</a-button
        >
      </a-form-item>
      <a-form-item style="margin-top: 24px">
        <div style="display: flex; align-items: top">
          <a-checkbox @change="onChange" class="ex" :checked="checked" style="margin-right: 10px"></a-checkbox>
          <p>
            登录即代表您同意<a class="blue" @click="lookHttp">《可信工作证用户服务协议》</a>
            ，未注册用户登录后自动生成账号
          </p>
        </div>
      </a-form-item>
    </a-form>
    <img src="../../assets/daBG.png" alt="" class="dabg" />
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { timeFix, setToken } from '@/utils/util'
import { doLogin, sendSms, newLogin } from '@/api/user'
import { validatePhone } from '@/utils/validate'

export default {
  components: {},
  data() {
    return {
      loginBtn: false,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        smsSendBtn: false,
      },
      checked: true,
      spinning: false,
      validFunction: (rule, value, callback) => {
        console.log(value)
        // for (let i = 0; i < arr.length; i++) {
        //   const single = arr[i]
        //   if (!REG.test(single)) {
        //     // 正则验证
        //     callback('请输入符合规范的域名/IP') // 校验未通过
        //     break
        //   }
        // }
        // if (arr.length > 10) {
        //   callback('最多添加10个') // 校验未通过
        // }

        // callback() // 校验通过
        if (value == '') {
          callback('请输入手机号')
        } else {
          if (validatePhone(value)) {
            this.phone = value
            this.isSendSms = true
            callback()
          } else {
            this.isSendSms = false
            callback('请输入正确的手机号')
          }
        }
      },
      phone: '',
      isSendSms: false,
      smsShow: true,
      count: '',
      timer: null,
      countText: '重新发送60秒',
    }
  },
  created() {},
  mounted() {
    console.log(process.env.VUE_APP_API_BASE_URL2)
    console.log(window.location.protocol + '//' + window.location.host)
  },
  methods: {
    // handler
    handleSubmit(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        Login,
      } = this

      state.loginBtn = true

      const validateFieldsKey = ['user_name', 'code']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          newLogin(values)
            .then((res) => {
              console.log(res)
              this.loginSuccess(res)
            })
            .catch((err) => {
              // this.requestFailed(err)
            })
            .finally(() => {
              state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },

    loginSuccess(res) {
      const redirect = decodeURIComponent(this.$route.query.redirect || '/')
      setToken('pssid', res.authorization)
      // 产品说统一回到首页去，不需要重定向了
      this.$router.replace({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: '登录成功',
        })
      }, 1000)
      this.isLoginError = false
    },
    requestFailed(err) {
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: err.msg,
        duration: 4,
      })
    },
    // 阅读点击选择框
    onChange(e) {
      console.log(`checked = ${e.target.checked}`)
      this.checked = e.target.checked
    },
    //lookHttp
    lookHttp() {
      let routeData = this.$router.resolve({ name: 'HttpText' })
      window.open(routeData.href, '_blank')
    },
    // 获取验证码
    getSms() {
      const TIME_COUNT = 60
      this.count = TIME_COUNT
      this.countText = '重新发送60秒'
      if (this.isSendSms) {
        this.spinning =  true
        sendSms({
          mobile: this.phone,
        })
          .then((res) => {
            if (!this.timer) {
              this.smsShow = false
              this.timer = setInterval(() => {
                if (this.count > 0 && this.count <= TIME_COUNT) {
                  this.count--
                  this.countText = `重新发送${this.count}秒`
                } else {
                  this.smsShow = true
                  clearInterval(this.timer)
                  this.timer = null
                }
              }, 1000)
            }
          })
          .catch((err) => {
            console.log(err)
          }).finally(() => {
            this.spinning = false
          })
      } else {
        this.$notification['error']({
          message: '错误',
          description: '请输入正确的手机号',
          duration: 4,
        })
      }
    },
  },
}
</script>

<style lang="less" scoped>
.main {
  position: relative;
  width: 100% !important;
  display: flex;
  align-items: top;
  justify-content: center;
  .dabg {
    max-width: 350px;
    max-height: 300px;
  }
}
.user-layout-login {
  min-width: 260px;
  width: 368px;
  // margin: 0 auto;
  margin-right: 100px;
  .sjh {
    width: 368px;
    margin: 0 auto 30px;
    h3 {
      font-size: 33px;
      color: rgba(0, 0, 0, 0.85);
      font-family: Avenir, 'Helvetica Neue', Arial, Helvetica, sans-serif;
      font-weight: 600;
      text-align: left;
      margin: 0;
    }
  }

  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
.link {
  border-top: 1px solid#d9d9d9;
  border-right: 1px solid#d9d9d9;
  border-bottom: 1px solid#d9d9d9;
  text-align: center;
  box-sizing: border-box;
  height: 40px;
  background: #fff;
}
.ex {
  color: #b3b8be;
}
.blue {
  color: #1890ff;
}
</style>
